import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录', requiresAuth: false }
    },
    {
      path: '/',
      redirect: '/videos'
    },
    {
      path: '/managers',
      name: 'managers',
      component: () => import('../views/ManagerListView.vue'),
      meta: { title: '管理员管理', requiresAuth: true }
    },
    {
      path: '/videos',
      name: 'videos',
      component: () => import('../views/VideoListView.vue'),
      meta: { title: '视频管理', requiresAuth: true }
    },
    {
      path: '/articles',
      name: 'articles',
      component: () => import('../views/ArticleListView.vue'),
      meta: { title: '文章管理', requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 后台管理系统`
  }
  
  // 如果是登录页面，直接放行
  if (to.path === '/login') {
    if (authStore.isLoggedIn) {
      // 已登录用户访问登录页，重定向到视频列表页
      next('/videos')
    } else {
      next()
    }
    return
  }
  
  // 其他页面需要验证登录状态
  if (!authStore.isLoggedIn) {
    next('/login')
  } else {
    next()
  }
})

export default router
